package de.slothsoft.commons.swing;

import static de.slothsoft.commons.res.CommonMessages.getString;
import static de.slothsoft.commons.swing.util.ControlUtil.createButton;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import de.slothsoft.commons.swing.util.GlassPaneUtil;
import de.slothsoft.commons.swing.util.GridBagUtil;
import de.slothsoft.commons.swing.util.KeyUtil;

public class KeyControl extends JPanel {

	private static final long serialVersionUID = 1L;

	private JLabel keyLabel;
	private JButton changeButton;

	private int key;

	public KeyControl() {
		createControls();
	}

	private void preparePanel() {
		setLayout(new GridBagLayout());
		setPreferredSize(new Dimension(400, 100));
		setOpaque(false);
	}

	protected void createControls() {
		preparePanel();

		this.keyLabel = createKeyLabel(this, 0, 0);
		this.changeButton = createButton(this, getString("KeyPanel.change"), 1, 0);
		this.changeButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				performKeyChange();
			}
		});
	}

	private static JLabel createKeyLabel(JComponent component, int x, int y) {
		JLabel label = new JLabel();
		component.add(label, GridBagUtil.textFieldDefaults(x, y));
		return label;
	}

	protected void performKeyChange() {
		this.keyLabel.setText(getString("KeyPanel.changeInfo"));
		this.keyLabel.setForeground(Color.RED);
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				GlassPaneUtil.lockWindowWithPane(getParentFrame(), new KeyGlassPane());
			}
		});
	}

	protected void performKeyTyped(int keyCode) {
		GlassPaneUtil.unlockWindow(getParentFrame());
		this.keyLabel.setForeground(null);
		if (keyCode == KeyEvent.VK_ESCAPE) {
			setKey(this.key);
		} else {
			setKey(keyCode);
		}
	}

	public int getKey() {
		return this.key;
	}

	public void setKey(int key) {
		this.key = key;
		this.keyLabel.setText(KeyUtil.getKeyName(key));
	}

	public JFrame getParentFrame() {
		return (JFrame) SwingUtilities.windowForComponent(this);
	}

	/*
	 * 
	 */

	class KeyGlassPane extends ConsumingGlassPane {

		private static final long serialVersionUID = 8072960293059189253L;

		public KeyGlassPane() {
			addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					performKeyTyped(e.getKeyCode());
				}
			});
		}
	}
}
